<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: class.product_konfigurator.php 543 2015-02-28 11:59:55Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 543 $
* 	zuletzt geaendert von:	$Author: $
* 	Datum:					$Date: 2015-02-28 11:59:55 +0000 (Sat, 28 Feb 2015) $
*
* 	extends by dirk.mueller (edv-mueller.com)
* 	http://www.itdotmedia.de
*
* --------------------------------------------------------------------------------------
* 	based on:
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
* 	Copyright (c) since 2011 SEO:mercari
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */
include_once(DIR_WS_CLASSES.'class.product_konfigurator.cart.php');

class product_konfigurator {
  var $product_id = '';
  public $enable = false;
	public $url = '';
	public $groups = array();
  var $tax_id = 0;
  var $cart = null;
  
  function product_konfigurator($product_id) {
    global $db;
    $this->product_id = $product_id;
    $query = $db->db_query("select products_id, products_tax_class_id from ".TABLE_PRODUCTS." p where p.products_id = '".$this->product_id."'");
    $this->tax_id = $query->fields['products_tax_class_id'];
    $this->cart = new product_konfigurator_cart($this);

		$query = $db->db_query("select konfigurator_option from ".TABLE_KONFIGURATOR_PRODUCT_OPTION." t "
													. "where t.product_id = '".$this->product_id."' and t.konfigurator_option_group = 'KONFIGURATOR_ENABLE' and t.konfigurator_option != 'false'");
		//echo_e($query->sql);
		if ($query->_numOfRows > 0) {
			$this->enable = true;
			$this->url = $query->fields['konfigurator_option'];
		}
		else
			$this->enable = false;
		
  }

  function _get_template_methode($option_group, $methode_name) {
    $option_class = array('filename' => 'class.'.$option_group['type'].'.php', 'name' => $option_group['type']);
    if ($option_group['type'] == 'ind') {
      $option_class['filename'] = 'ind.class.'.strtolower($option_group['id'].'.php');
      $option_class['name'] = strtolower($option_group['id']);
    }
    
    if (substr(DIR_WS_INCLUDES, 0, 1) == '/')
	    $file_base = DIR_WS_INCLUDES;
	  else
	    $file_base = DIR_FS_CATALOG.DIR_WS_INCLUDES;
	    
    $file_name = $file_base.'modules/product_konfigurator/'.$option_class['filename'];
    if(!file_exists($file_name))
      return false;

    include_once($file_name);
    $cls = new $option_class['name']();
    
    if (method_exists($cls, $methode_name)){
      $cls->set_group($option_group);
      return array($cls, $methode_name);
    }
    else
      return false;
  }

  function get_groups($group = '') {
		global $db;
		
		if ($group == '' && !empty($this->groups)) return $this->groups;

		$groups = array();

		$sql = "
      select
      	og.konfigurator_optiongroups_id, og.konfigurator_optiongroups_name,
      	og.konfigurator_optiongroups_type, po.is_default have_to
      from
      	".TABLE_KONFIGURATOR_PRODUCT_OPTION." po
      	inner join ".TABLE_KONFIGURATOR_OPTIONGROUPS." og
      		on po.konfigurator_option_group = og.konfigurator_optiongroups_id
      where
      	po.konfigurator_option = 'HAVE_TO'
      	and po.product_id = '".$this->product_id."'
        " . ($group == ''
          ? "and (og.konfigurator_optiongroups_type <> 'info' and not og.konfigurator_optiongroups_type like 'filter-%')"
          : "and og.konfigurator_optiongroups_id = '" . $group . "'") . "
      order by
      	og.konfigurator_optiongroups_sort";
    $query = $db->db_query($sql, true);

    $groups['main'] = array(
      'id'      => 'main',
      'name'    => 'BASICs',
      'type'    => 'maingroup',
      'have_to' => false
    );

		if($query->_numOfRows > 0){
			while(!$query->EOF){
        $groups[$query->fields['konfigurator_optiongroups_id']] = array(
          'id'      => $query->fields['konfigurator_optiongroups_id'],
          'name'    => $query->fields['konfigurator_optiongroups_name'],
          'type'    => $query->fields['konfigurator_optiongroups_type'],
          'have_to' => $query->fields['have_to']
        );
        $query->moveNext();
  		}
    }
    
    // remove groups w/o options
    $sql = "
    	select 		konfigurator_option_group, count(*) _c
    	from 			".TABLE_KONFIGURATOR_PRODUCT_OPTION." po
    	where			po.product_id = '".$this->product_id."'
    						and konfigurator_option_group in ('" . implode("', '", array_keys($groups)) . "')
    	group by	konfigurator_option_group";
    $query = $db->db_query($sql, true);
		if($query->_numOfRows > 0){
			while(!$query->EOF) {
				if ($query->fields['_c'] < 2) 
					unset( $groups[strToUpper($query->fields['konfigurator_option_group'])] );
        $query->moveNext();
			}
		}

    if ($group == '')
			$this->groups = $groups;
		else
			$this->groups = array();
    return $groups;
  }

  function getProductKey($post) {
    $groups = $this->get_groups();
    $key = $this->product_id;
    foreach($post as $id => $val) {
      if (isset($groups[$id]))
        $key .= '{'.$id.'}'. $val;
    }
    return $key;
  }

  function parseProductKey($key) {
    $param = array();
    $items = explode('{', $key);
    $product_id = array_shift($items);

    foreach($items as $no => $val) {
      list($k, $v) = explode('}', $val);
      $param[$k] = $v;
    }
    return $param;
  }


  function assign_template(&$smarty_module_option, $option_group, $with_form_action = true) {
    if (($func = $this->_get_template_methode($option_group, 'assign_template')) !== false) {
      call_user_func($func, $smarty_module_option, $this->product_id, $with_form_action);
    };
  }

  function print_js($with_form_action = true) {
    $option_types = array();
    $option_groups = $this->get_groups();
    foreach($option_groups as $id => $option_group) {
      if (!in_array($option_group['type'], $option_types)) {
        if (($func = $this->_get_template_methode($option_group, 'print_js_base')) !== false) {
            echo "\n/* load Konfigurator base - ".$option_group['type']." */\n";
            call_user_func($func, $this->product_id, $with_form_action);
            $option_types[] = $option_group['type'];
        }
      }

      if (($func = $this->_get_template_methode($option_group, 'print_js')) !== false) {
        echo "\n/* load Konfigurator - ".$option_group['id']." */\n";
        call_user_func($func, $this->product_id, $with_form_action);
      };
 		}
  }
  
  function print_js_just_layer() { $this->print_js(false); }
  
  function eval_values() {
    return '';
  }
  
  function _add_price(&$price, $id) {
    $price['all']['netto'] += $price[$id]['netto'];
    $price['all']['tax']['value'] += $price[$id]['tax']['value'];
    $price['all']['brutto'] += $price[$id]['brutto'];
    return $price;
  }
  
  function get_price($post) {
    $option_groups = $this->get_groups();
    $price = array();
    $price_default = array(
      'netto' => 0,
      'tax' => array(
        'id'    => $this->tax_id,
        'rate'  => get_tax_rate($this->tax_id),
        'value' => 0),
      'brutto' => 0);
    $price['all'] = $price_default;

    foreach($option_groups as $option_group) {
      if (($func = $this->_get_template_methode($option_group, 'get_price')) !== false) {
        $price[$option_group['id']] = call_user_func($func, $this->product_id, $price_default, $post);
        $this->_add_price($price, $option_group['id']);
      };
    }
		//echo_e($price);
    
    return $price;
  }

  function get_description($post) {
		global $price;
		if (!is_object($price)) {
			include(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.price.php');
			$price = new price($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);
		}
			
    $option_groups = $this->get_groups();
		$prices = $this->get_price($post);

    $description = array();
    foreach($option_groups as $option_group) {
      if (($func = $this->_get_template_methode($option_group, 'get_description')) !== false) {
        $description[$option_group['id']] = call_user_func($func, $this->product_id, $post);
				if ($prices[$option_group['id']]['netto'] == 0)
					$description[$option_group['id']]['price'] = '';
				else
					$description[$option_group['id']]['price'] 
						= ($prices[$option_group['id']]['netto'] > 0 ? '+' : '')
						. $price->format($_SESSION['customers_status']['customers_status_show_price_tax'] != 0 ? $prices[$option_group['id']]['brutto'] : $prices[$option_group['id']]['netto'], true);
      };
    }

		return $description;
  }

}
if(!defined('TABLE_KONFIGURATOR_OPTIONGROUPS')) define('TABLE_KONFIGURATOR_OPTIONGROUPS', DB_PREFIX.'konfigurator_optiongroups');
if(!defined('TABLE_KONFIGURATOR_OPTIONS')) define('TABLE_KONFIGURATOR_OPTIONS', DB_PREFIX.'konfigurator_options');
if(!defined('TABLE_KONFIGURATOR_PRODUCT_OPTION')) define('TABLE_KONFIGURATOR_PRODUCT_OPTION', DB_PREFIX.'konfigurator_product_option');
if(!defined('TABLE_KONFIGURATOR_CATEGORY_OPTION')) define('TABLE_KONFIGURATOR_CATEGORY_OPTION', DB_PREFIX.'konfigurator_category_option');
if(!defined('TABLE_KONFIGURATOR_PRODUCT_TEMPLATES')) define('TABLE_KONFIGURATOR_PRODUCT_TEMPLATES', DB_PREFIX.'konfigurator_product_templates');
